package com.guocheng.config.shiro;

import com.guocheng.modules.login.model.po.User;
import com.guocheng.modules.login.service.MenuService;
import com.guocheng.modules.login.service.UserService;
import com.guocheng.modules.login.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

public class ShiroRealm extends AuthorizingRealm {

    //注入密码比较器
    public ShiroRealm() {
        //缓存管理，密码比较器
        super(null, new Comparator());
    }

    @Autowired
    private UserService userSerivce;

    @Autowired
    private MenuService menuService;

    /**
     * 执行认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        //编写shiro判断逻辑，判断用户名和密码
        //1.判断用户名  token中的用户信息是登录时候传进来的
        UsernamePasswordToken token = (UsernamePasswordToken)arg0;

        User user = userSerivce.selectByUsername(token.getUsername());

        if(user==null){
            //用户名不存在
            return null;//shiro底层会抛出UnKnowAccountException
        }
        if(user.getStatus()!=1){
            throw new AuthenticationException("用户已被禁用");
        }
        //2.判断密码不相同就抛出IncorrectCredentialsException异常。
        String password = user.getPassword();
        user.setPassword(null);
        return new SimpleAuthenticationInfo(user,password,this.getName());
    }

    /**
     * 执行授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //到数据库查询当前登录用户的授权字符串
        //获取当前登录用户
        User user = (User)principalCollection.getPrimaryPrincipal();
        List<String> menus = menuService.selectByUserId(user.getId());
        HashSet<String> permissions = new HashSet<>(menus);
        //菜单授权
        info.addStringPermissions(permissions);

        return info;
    }


}